package utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import play.Play;
import play.libs.Codec;
import services.SystemParamService;
import vos.ResponseInfo;

import com.aton.db.Config;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;

/**
 * 语音播报工具类
 * @author wangshaoming
 *
 */
public class BroadUtils {
	private static final SimpleDateFormat dateFormater = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	
	
	public static final Logger log=LoggerFactory.getLogger("broad");
	
	
	public static String postBroad(String content,String tone,String speed,String fileName){
		tone=StringUtils.isEmpty(tone)?"cn_baisong_common":tone;
		speed=StringUtils.isEmpty(speed)?"5":speed;
		String videoPath="";
		
		String url=SystemParamService.getValueByCacheId(BizConstants.PARAM_MAP.get("SSH_RESTART_TTS_IP"));
		String port=SystemParamService.getValueByCacheId(BizConstants.PARAM_MAP.get("BROADCAST_PORT"));
		String dev_key=SystemParamService.getValueByCacheId(BizConstants.PARAM_MAP.get("BROADCAST_DEV_KEY"));
		String app_key=SystemParamService.getValueByCacheId(BizConstants.PARAM_MAP.get("BROADCAST_X_APP_KEY"));
		String sdk_version=SystemParamService.getValueByCacheId(BizConstants.PARAM_MAP.get("BROADCAST_X_SDK_VERSION"));
		String x_udid=SystemParamService.getValueByCacheId(BizConstants.PARAM_MAP.get("BROADCAST_X_UDID"));
		String x_tid=SystemParamService.getValueByCacheId(BizConstants.PARAM_MAP.get("BROADCAST_X_TID"));
		String x_eid=SystemParamService.getValueByCacheId(BizConstants.PARAM_MAP.get("BROADCAST_X_EID"));
		try{
			log.info("---引擎发送：***********************");
			log.info("---数据长度："+content.length());
			long nowTime = TimeConvert.getNowTimeLong();
			URL action = new URL("http://"+url+":"+port+"/tts/SynthText");
			HttpURLConnection http=(HttpURLConnection)action.openConnection();
			http.setRequestMethod("POST");
			http.setRequestProperty("Connection", "close");
			http.setRequestProperty("Content-type", "application/json;charset=UTF-8");
			http.setRequestProperty("x-app-key", app_key);
			http.setRequestProperty("x-sdk-version", sdk_version);
			http.setRequestProperty("x-request-date", dateFormater.format(new Date()));
			String ssionKey=Codec.hexMD5(dateFormater.format(new Date())+dev_key);
			http.setRequestProperty("x-session-key",ssionKey);
			http.setRequestProperty("x-task-config","capkey=tts.cloud.synth,domain=common,property="+tone+",speed="+speed+",audioformat=mp3");
			http.setRequestProperty("x-udid",x_udid);
			http.setRequestProperty("x_tid",x_tid);
			http.setRequestProperty("x_eid",x_eid);
			http.setRequestProperty("Content-Length", Long.toString(content.length()));
			http.setRequestProperty("Accept", "*/*");
			http.setRequestProperty("Accept-Encoding", "identity");
			http.setDoOutput(true);
			http.setDoInput(true);
//			http.setReadTimeout(30000);
//			http.setConnectTimeout(40000);
			//设置超时时间
			System.setProperty("sun.net.client.defaultConnectTimeout", "40000");
			System.setProperty("sun.net.client.defaultReadTimeout", "30000");
			http.connect();
			OutputStream os=http.getOutputStream();
			os.write(content.getBytes("UTF-8"));
			os.flush();
			os.close();
			if(http.getResponseCode()==200){
				Long costTime = TimeConvert.getTimeSpace(nowTime);
				log.info("---引擎接收：耗时：" + costTime );
				nowTime = TimeConvert.getNowTimeLong();
				int length=http.getContentLength();
				InputStream is=http.getInputStream();
				byte[] jsonBytes=new byte[length];
				log.info("数据流中的长度"+Integer.toString(length));
				//由于网络流波动，造成流不连续，所以循环读取
				int count=0;
				while(count<length){
					int out=is.read(jsonBytes,count,length-count);
					count+=out;
					if(out==-1){
						break;
					}
				}
				String message=new String(jsonBytes,"UTF-8");
				if(!message.contains("</ResponseInfo>")){
					return "";
				}
				String xml=message.substring(message.indexOf("<?xml"),
						message.indexOf("</ResponseInfo>")+"</ResponseInfo>".length());
				
				XStream xstream=new XStream(new DomDriver());
				xstream.processAnnotations(ResponseInfo.class);
				ResponseInfo info=(ResponseInfo) xstream.fromXML(xml);
				costTime = TimeConvert.getTimeSpace(nowTime);
				log.info("---解析XMl：耗时：" + costTime );
				if("Success".equals(info.getResCode())){
					//截取字符串后的二进制音频流
					nowTime = TimeConvert.getNowTimeLong();
					int xmlLength=xml.getBytes("UTF-8").length;
					log.info(Integer.toString(xmlLength));
					byte[] video=new byte[jsonBytes.length-xmlLength];
					int k=0;
					for(int i=xmlLength;i<jsonBytes.length;i++){
						video[k]=jsonBytes[i];
						k++;
					}
					log.info(Integer.toString(video.length));
					String path=Play.applicationPath + File.separator;
					videoPath=BizConstants.FILE_TEMP_PATH+fileName+".mp3";
					File file=new File(path +videoPath);
					if(!file.exists()){
						file.createNewFile();
					}
					FileOutputStream byteos=new FileOutputStream(path +videoPath);
					byteos.write(video);
					costTime = TimeConvert.getTimeSpace(nowTime);
					log.info("---解析音频：耗时：" + costTime );
					byteos.close();
				}
				else{
					log.info(info.getErrorNo());
				}
			}
		}catch(MalformedURLException e){
			e.printStackTrace();
			return "";
		} catch (ProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return "";
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return "";
		}
		return videoPath;
	}
	/**
	 * 获取文本中的标点
	 * @param content
	 * @return
	 */
	public static int getLastPunc(String content){
		int[] puncs=new int[8];
		puncs[0]=content.lastIndexOf(",");
		puncs[1]=content.lastIndexOf("。");
		puncs[2]=content.lastIndexOf("，");
		puncs[3]=content.lastIndexOf(".");
		puncs[4]=content.lastIndexOf("！");
		puncs[5]=content.lastIndexOf("!");
		puncs[6]=content.lastIndexOf("?");
		puncs[7]=content.lastIndexOf("？");
		int last=puncs[0];
		for(int i=0;i<puncs.length;i++){
			if(puncs[i]>last){
				last=puncs[i];
			}
		}
		return last;
	}
}
